#include "seqiot.h"
#include "sqlite.h"

data_catalog_t *data_catalog_new() {
    return z_calloc(1, sizeof(data_catalog_t));
}

void data_catalog_free(data_catalog_t *catalog) {
    if (!catalog) return;

    z_free(catalog);
}

void read_row_catalog(sqlite3_stmt *stmt, data_catalog_t *rs) {
    int idx = 0;
    rs->catalog = sqlite3_column_int(stmt, idx++);
    rs->read.period = sqlite3_column_int(stmt, idx++);
    rs->read.delay = sqlite3_column_int(stmt, idx++);
    rs->pub.period = sqlite3_column_int(stmt, idx++);
    rs->pub.delay = sqlite3_column_int(stmt, idx++);
}

int read_stmt_catalogs(sqlite3 *db, vector_t *catalogs) {
    int rc;
    sqlite3_stmt *stmt = NULL;
    const char *sql = "SELECT c.id, r.period pr, r.delay dr, p.period pp, p.delay dp\n"
                      "FROM data_catalog c\n"
                      "JOIN interval r ON c.read_interval = r.id\n"
                      "JOIN interval p ON c.pub_interval = p.id";

    rc = sqlite3_prepare(db, sql, -1, &stmt, NULL);
    if (SQLITE_OK != rc) {
        sqlite_check(db);
        goto err;
    }

    while (SQLITE_ROW == sqlite3_step(stmt)) {
        data_catalog_t *catalog = data_catalog_new();
        read_row_catalog(stmt, catalog);
        vector_add(catalogs, catalog);
    }

    err:
    sqlite3_finalize(stmt);
    return rc;
}
